package com.example.jdimust.totalbase;

import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.jdimust.R;
import com.example.jdimust.ledger.LedgerBean;
import com.example.jdimust.register.NetworkRequest;
import com.example.jdimust.totalbase.BaseBean;
import com.example.jdimust.util.ACache;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

import lecho.lib.hellocharts.listener.ColumnChartOnValueSelectListener;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Column;
import lecho.lib.hellocharts.model.ColumnChartData;
import lecho.lib.hellocharts.model.PieChartData;
import lecho.lib.hellocharts.model.SliceValue;
import lecho.lib.hellocharts.model.SubcolumnValue;
import lecho.lib.hellocharts.util.ChartUtils;
import lecho.lib.hellocharts.view.ColumnChartView;
import lecho.lib.hellocharts.view.PieChartView;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Author: MaZongyang
 * Date: 2021/5/22/0022 18:49
 * Description:统计数据页面
 */
public class DataStatisticsActivity  extends AppCompatActivity {

    private ColumnChartView chart;            //柱状图的自定义View
    private ColumnChartData data;
    private final boolean hasAxes = true;            //是否有坐标轴
    private boolean hasAxesNames = true;       //是否有坐标轴的名字
    private boolean hasLabels = true;          //柱子上是否显示标识文字
    private boolean hasLabelForSelected = false;    //柱子被点击时，是否显示标识的文字



    private PieChartView piechart;        //存放柱状图数据的对象
    private PieChartData datapie;
    private boolean hasLabelsOutside = false;           //标签是否在扇形外面
    private boolean hasCenterCircle = false;            //是否有中心圆
    private boolean hasCenterText1 = true;             //是否有中心的文字
    private boolean hasCenterText2 = true;             //是否有中心的文字2
    private boolean isExploded = false;                  //是否是炸开的图像

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_datasta);
        ACache acache = ACache.get(this);//创建ACache组件
        Spinner spinner = (Spinner)findViewById(R.id.sp_sj);
//        Button bt_getdata = (Button)findViewById(R.id.getdata);
        piechart = (PieChartView) findViewById(R.id.piechart);
        ArrayList<String> lednamelist = new ArrayList<>();
        ArrayList<String> ledhashlist = new ArrayList<>();
        ArrayList<Integer> countsize = new ArrayList<>();

        try {
            OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象
            Request request = new Request.Builder()
                    .url("https://hzy.graduationproject.xyz/GetMessage/ledger")//请求接口。如果需要传参拼接到接口后面。
                    .build();//创建Request 对象
            Response response = null;
            response = client.newCall(request).execute();//得到Response 对象
            int ledsize = 0;

            if (response.isSuccessful()) {
                String getallled = response.body().string();
                Gson gson = new Gson();
                LedgerBean ledbean = gson.fromJson(getallled,LedgerBean.class);
                ledsize = ledbean.getResult().size();
                for (LedgerBean.ResultDTO resultDTO : ledbean.getResult()) {
                    lednamelist.add(resultDTO.getLedgerName());
                    ledhashlist.add(resultDTO.getLedgerHash());
                }
                acache.put("lednamelist",lednamelist);
                acache.put("ledhashlist",ledhashlist);
//                System.out.println(ledhashlist.get(0)+"\n"+lednamelist.get(0)+"\n"+ledsize);
            }
        } catch (Exception e) {
//            e.printStackTrace();
            System.out.println("somethings");
        }

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, lednamelist);
        spinner.setPrompt("请选择要查看的账本数据");
        spinner.setAdapter(adapter);
        initDatapie(lednamelist);
        String temp = ledhashlist.get(0);
        final String[] rejson = {null};
        final int[] x = {0};
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                x[0] = position;
                rejson[0] = NetworkRequest.getaccount("/base?ledgerHash=",ledhashlist.get(x[0]),"");
                Gson gson = new Gson();
                BaseBean basebean = gson.fromJson(rejson[0],BaseBean.class);
                countsize.add(basebean.getResult().getBlockchainHeight());
                countsize.add(basebean.getResult().getTotalNumberOfTransactions());
                countsize.add(basebean.getResult().getTotalNumberOfUsers());
                countsize.add(basebean.getResult().getTotalNumberOfDataAccounts());
                countsize.add(basebean.getResult().getTotalNumberOfContracts());
                initView();
                initData();
                initEvent(countsize);
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        System.out.println(ledhashlist.get(x[0]));


//        bt_getdata.setOnClickListener(new View.OnClickListener(){
//            @Override
//            public void onClick(View view) {
//            }
//        });





    }

    private void initDatapie(List lednamelist) {
        int numValues = lednamelist.size();
        //初始化数据
        List<SliceValue> values = new ArrayList<SliceValue>();
        for (int i = 0; i < numValues; ++i) {
            SliceValue sliceValue = new SliceValue((Integer) lednamelist.size(), ChartUtils.pickColor());
            values.add(sliceValue);
        }

        datapie = new PieChartData(values);
        datapie.setHasLabels(hasLabels);          //柱子上是否显示标识文字
        datapie.setHasLabelsOnlyForSelected(hasLabelForSelected);    //柱子被点击时，是否显示标识的文字
        datapie.setHasLabelsOutside(hasLabelsOutside);           //标签是否在扇形外面
        datapie.setHasCenterCircle(hasCenterCircle);            //是否有中心圆
        datapie.setHasCenterCircle(true);
        datapie.setHasLabelsOutside(true);

        if (isExploded) {
            datapie.setSlicesSpacing(24);
        }

        if (hasCenterText1) {
            datapie.setCenterText1("账本总数");//设置中心文字1
            datapie.setCenterText1Color(Color.BLACK);
            //中心圆的文本大小
            datapie.setCenterText1FontSize(24);
            //文本字体大小
            datapie.setValueLabelTextSize(40);

        }

        if (hasCenterText2) {
            datapie.setCenterText2("totalNumberOfLedgers");//设置中心文字2
            datapie.setCenterText2Color(Color.BLACK);
        }

        piechart.setPieChartData(datapie);
    }


    private void initView() {
        chart = (ColumnChartView) findViewById(R.id.chart);
    }

    private void initData() {
        chart.setOnValueTouchListener(new ValueTouchListener());
    }

    private void initEvent(List count) {
        int numSubcolumns = 1;
        int numColumns = 5;
        // Column can have many subcolumns, here by default I use 1 subcolumn in each of 8 columns.
        List<Column> columns = new ArrayList<Column>();
        List<SubcolumnValue> values;
        for (int i = 0; i < numColumns; ++i) {
            values = new ArrayList<SubcolumnValue>();
            for (int j = 0; j < numSubcolumns; ++j) {
                values.add(new SubcolumnValue((Integer) count.get(i), ChartUtils.pickColor()));
            }

            Column column = new Column(values);
            column.setHasLabels(hasLabels);//柱子上是否显示标识文字
            column.setHasLabelsOnlyForSelected(hasLabelForSelected);//柱子被点击时，是否显示标识的文字
            columns.add(column);
        }

        List<AxisValue> axis_X_Values = new ArrayList<>();
        axis_X_Values.add(new AxisValue(0,new String("区块高度").toCharArray()));
        axis_X_Values.add(new AxisValue(1,new String("交易数量").toCharArray()));
        axis_X_Values.add(new AxisValue(2,new String("用户数量").toCharArray()));
        axis_X_Values.add(new AxisValue(3,new String("账户数量").toCharArray()));
        axis_X_Values.add(new AxisValue(4,new String("合约数量").toCharArray()));



        data = new ColumnChartData(columns);

        if (hasAxes) {
            Axis axisX = new Axis();
            Axis axisY = new Axis().setHasLines(true);
            if (hasAxesNames) {
                axisX.setName("统计名称");
                axisX.setValues(axis_X_Values);
                axisY.setName("具体数量");
                axisX.setLineColor(Color.BLACK);
                axisX.setTextColor(Color.BLACK);
                axisY.setLineColor(Color.BLACK);
                axisY.setTextColor(Color.BLACK);
            }
            data.setAxisXBottom(axisX);
            data.setAxisYLeft(axisY);
        } else {
            data.setAxisXBottom(null);
            data.setAxisYLeft(null);
        }
//最后将所有值显示在View中
//        chart.setColumnChartData(data);
        chart.setColumnChartData(data);


    }

//    isXValues); //填充X轴的坐标名称 data.setAxisXBottom(axisX); //x 轴在底部 //data.setAxisXTop(axisX); //x 轴在顶部 axisX.setHasLines(true); //x 轴





    /**
     * 图像的监听
     */
    private class ValueTouchListener implements ColumnChartOnValueSelectListener {

        @Override
        public void onValueSelected(int columnIndex, int subcolumnIndex, SubcolumnValue value) {
            showToast("Selected: " + value);
        }

        @Override
        public void onValueDeselected() {

        }

    }


    Toast toast;

    public void showToast(String msg) {
        if (toast == null) {
            toast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
        } else {
            toast.setText(msg);
        }
        toast.show();
    }


}